#pragma once
#include <iostream>
#include <unistd.h>
#include "Log.hpp"
#include "Init.hpp"

extern Log lg;

Init init;

class Task
{
public:
    Task(const int &sockfd, const std::string &clientip, const uint16_t &clientport) : sockfd_(sockfd), clientip_(clientip), clientport_(clientport)
    {
    }
    Task()
    {
    }
    void run()
    {
        char buffer[4096];
        ssize_t n = read(sockfd_, buffer, sizeof(buffer));
        if (n < 0)
        {
            lg(Warning, "read fail, sockfd: %d, client ip: %s, client port: %d", sockfd_, clientip_.c_str(), clientport_);
        }
        else if (n == 0)
        {
            lg(Info, "%s:%d quit, server sockfd: %d closed", clientip_.c_str(), clientport_, sockfd_);
        }
        else
        {
            buffer[n] = '\0';
            std::string input(buffer);
            if (!input.empty() && input.back() == '\n')
            {
                input.pop_back();
            }
            std::cout << "client key#" << input << std::endl;
            std::string echo_string = init.capital_of_country(input);
            n = write(sockfd_, echo_string.c_str(), echo_string.size()); 
        }
        close(sockfd_);
    }
    void operator()()
    {
        run();
    }

private:
    int sockfd_;
    std::string clientip_;
    uint16_t clientport_;
};